package com.cd.sendRequest.controller;

import com.cd.common.config.ProjectConfig;
import com.cd.common.constant.Constants;
import com.cd.common.controller.BaseController;
import com.cd.common.domain.AjaxResult;
import com.cd.common.util.StringUtils;
import com.cd.sendRequest.jpa.repo.HomeBannerRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 暴露的对外的接口
 */
@RestController
@RequestMapping("/show")
public class ShowController extends BaseController {

    @Autowired
    private HomeBannerRepo homeBannerRepo;

    @GetMapping("/getUrl/{type}/{number}")
    public AjaxResult getUrl(@PathVariable String type,
                             @PathVariable Integer number) {
        try {
            String filePath = homeBannerRepo.findByTypeAndOrder(type, number).getImgPath();
            // 1. 安全校验
            if (filePath.contains("..")) {
                return error("非法路径");
            }

            // 2. 检查文件扩展名
//            if (!isAllowedExtension(filePath)) {
//                return ResponseEntity.badRequest().body("不支持的文件类型");
//            }

            // 3. 构建完整路径
            //Path fullPath = Paths.get(baseDir).resolve(filePath).normalize();
            String localPath = ProjectConfig.getProfile();
            String downloadPath = localPath + StringUtils.substringAfter(filePath, Constants.RESOURCE_PREFIX);
            Path fullPath = Paths.get(downloadPath).normalize();
            // 4. 验证文件存在且可读
            if (!Files.exists(fullPath) || !Files.isReadable(fullPath)) {
                return error("文件不存在");
            }

            // 5. 返回文件信息
            Map<String, Object> response = new HashMap<>();
            response.put("url", filePath); // 相对路径
            response.put("size", Files.size(fullPath));
            response.put("mimeType", Files.probeContentType(fullPath));
            response.put("lastModified", Files.getLastModifiedTime(fullPath).toMillis());

            return success(response);

        } catch (Exception e) {
            return error("文件服务异常: " + e.getMessage());
        }
    }
}
